/* eslint-disable no-useless-escape */
import { Children, cloneElement } from "react";
import Axios from 'axios'
import LocalStorage from './localStorage'
let basePath = 'http://api.tianapi.com'
// 防抖
// 多次触发的情况下只触发一次
function debounce(fn, delay) {
    let timeout = null;
    return function (event) {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            fn.apply(this, arguments);
        }, delay);
    };
}
// 节流
// 多次触发的情况下减少触发的次数
function throttle(fn, delay) {
    let valid = true
    return function (e) {
        if (!valid) {
            return false
        }
        valid = false
        setTimeout(() => {
            fn(e)
            valid = true;
        }, delay)
    }
}
// 判断平台
function isMobile() {
    let Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
    let arr = Agents.map(val => {
        if (navigator.userAgent.indexOf(val) > 0) {
            return true
        } else {
            return false
        }
    })
    if (arr.includes(true)) return true
    return false;
}
// children遍历
function childrenMap(children, props){
    return Children.map(children, (child, index) => {
        // console.log(typeof child.type)
        if(typeof child.type === 'function' || typeof child.type === 'object'){
            return cloneElement(child, {
                index,
                ...props
            });
        }else{
            return cloneElement(child);
        }

    })
}
// 单位转换
function px2rem (px){
    let fontSize = document.getElementsByTagName('html')[0].style.fontSize.split('px')[0]
    if(typeof px === 'string'){
        if(px.includes('px') > -1){
            let val = px.split('px')[0]
            return `${Number(val)/Number(fontSize)}rem`
        }
    }
    return `${px/Number(fontSize)}rem`
}
// 格式化时间   秒   --->   --:--:--
function formatSeconds(value) {
    let theTime = parseInt(value);// 秒
    let theTime1 = 0;// 分
    let theTime2 = 0;// 小时
    if (theTime >= 60) {
        theTime1 = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (theTime1 >= 60) {
            theTime2 = parseInt(theTime1 / 60);
            theTime1 = parseInt(theTime1 % 60);
        }
    }
    let result = "" + parseInt(theTime);
    if(result < 10){
        result = '0' + result;
    }
    if (theTime1 > 0) {
        result = "" + parseInt(theTime1) + ":" + result;
        if(theTime1 < 10){
            result = '0' + result;
        }
    }else{
        result = '00:' + result;
    }
    if (theTime2 > 0) {
        result = "" + parseInt(theTime2) + ":" + result;
        if(theTime2 < 10){
            result = '0' + result;
        }
    }else{
        result = '00:' + result;
    }
    return result;
}

//全屏
function fullScreen() {
    var element = document.documentElement;
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    }
}

//退出全屏 
function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    }
}
// 状态管理
function stateManage(obj){

}

function setLocalStorage(key, val){
    localStorage.setItem(key, JSON.stringify(val))
}
function getLocalStorage(key){
    let val = localStorage.getItem(key)
    return JSON.parse(val)
}

async function get(url, params){
    let path
    if(!isURL(url))
        path = basePath + url
    if(isURL(url))
        path = url
    return await Axios.get(path,{
        params:params
    }).then(res=>res.data)
}

function isURL(str_url) { // 验证url
    var strRegex = "^((https|http){1}://)" +
        "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
        + "|" // 允许IP和DOMAIN（域名）
        + "([0-9a-z_!~*'()-]+\.){1}" // 域名- www.
        + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
        + "[a-z]{2,6})" // first level domain- .com or .museum
        + "(:[0-9]{1,4})?" // 端口- :80
        + "((/?)|" // a slash isn't required if there is no file name
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        var re = new RegExp(strRegex);
        return re.test(str_url);
}

function getSearchWord(type, keyWord){
    switch(type){
        case 'Google':
            return 'http://clients1.google.com/complete/search?hl=zh&output=toolbar&q=' + keyWord
        case 'Baidu':
            return `http://suggestion.baidu.com/su?wd=${keyWord}&cb=window.baidu.sug`
        case 'Sougou':
            return `http://w.sugg.sogou.com/sugg/ajaj_json.jsp?key=${keyWord}&type=web`
        case 'so':
            return `https://sug.so.360.cn/suggest?callback=suggest_so&word=${keyWord}`
        case 'Bing':
            return `https://api.bing.com/qsonhs.aspx?type=cb&q=${keyWord}`
        default:
            return ''
    }
}
//将16进制颜色转换成rgb
function hex2rgb(hex) {
    hex = hex.substring(1);
    hex = hex.toLowerCase();
    let rgb = new Array();
    for(let x=0;x<3;x++){
        rgb[0]=hex.substr(x*2,2);
        rgb[3]="0123456789abcdef";
        rgb[1]=rgb[0].substr(0,1);
        rgb[2]=rgb[0].substr(1,1);
        rgb[20+x]=rgb[3].indexOf(rgb[1])*16+rgb[3].indexOf(rgb[2]);
    }
    //return "rgb(" +b[20]+","+b[21]+","+b[22]+ ")";
    return rgb[20]+","+rgb[21]+","+rgb[22];
}
// rgba转换16进制

function colorHex(color) {
    var rgb = color.split(',');
    var r = parseInt(rgb[0].split('(')[1]);
    var g = parseInt(rgb[1]);
    var b = parseInt(rgb[2].split(')')[0]);

    var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    return hex;
}

let Util = {
    debounce,
    throttle,
    isMobile,
    childrenMap,
    px2rem,
    formatSeconds,
    fullScreen,
    exitFullscreen,
    stateManage,
    setLocalStorage,
    getLocalStorage,
    get,
    isURL,
    getSearchWord,
    hex2rgb,
    LocalStorage,
    colorHex
}
export {
    debounce,
    throttle,
    isMobile,
    childrenMap,
    px2rem,
    formatSeconds,
    fullScreen,
    exitFullscreen,
    stateManage,
    setLocalStorage,
    getLocalStorage,
    get,
    isURL,
    getSearchWord,
    hex2rgb,
    LocalStorage,
    colorHex
}
export default Util